package cn.qn.service.impl.member;

import cn.qn.base.PageVO;
import cn.qn.dto.member.MemberAccountDTO;
import cn.qn.dto.member.MemberAccountQueryDTO;
import cn.qn.exceptions.BizException;
import cn.qn.mapper.member.MemberMapper;
import cn.qn.moudle.security.MemberAccount;
import cn.qn.moudle.security.MemberRole;
import cn.qn.moudle.security.Permission;
import cn.qn.moudle.security.Role;
import cn.qn.repository.member.MemberAccountRepository;
import cn.qn.repository.member.MemberRoleRepository;
import cn.qn.repository.security.PermissionRepository;
import cn.qn.repository.security.RoleRepository;
import cn.qn.service.member.MemberService;
import com.github.miemiedev.mybatis.paginator.domain.PageBounds;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author: Bryant
 * @date: 2019/5/24
 * @description:
 */
@Service
@com.alibaba.dubbo.config.annotation.Service(interfaceClass = MemberService.class)
public class MemberServiceImpl implements MemberService {

    @Autowired
    private MemberAccountRepository memberAccountRepository;
    @Autowired
    private PermissionRepository permissionRepository;
    @Autowired
    private RoleRepository roleRepository;
    @Autowired
    private MemberRoleRepository memberRoleRepository;
    @Resource
    private MemberMapper memberMapper;

    @Override
    public MemberAccount findMemberAccountByUserId(String userId) {
        return memberAccountRepository.findMemberAccountByUserId(userId);
    }

    @Override
    public MemberAccount findMemberAccountById(Integer id) {
        return memberAccountRepository.findById(id).get();
    }

    /**
     * @return
     */
    @Override
    public List<Permission> finAllPermission() {
        return permissionRepository.findAll();
    }

    @Override
    public List<Role> findRolesByPermissionId(Integer permissionId) {
        return roleRepository.findRolesByPermissionId(permissionId);
    }

    @Override
    public List<Role> findRoleByMemberId(String userId) {
        return roleRepository.findByUserId(userId);
    }

    @Override
    public PageVO<MemberAccountDTO> pageQueryMembers(MemberAccountQueryDTO query) {
        PageBounds pb = new PageBounds(query.getPageBounds().getPage(), query.getPageBounds().getLimit());
        List<MemberAccountDTO> page = memberMapper.pageQueryMembers(query, pb);
        page.forEach(m->{
            m.setRoleIds(memberRoleRepository.findRoleIdsByUserId(m.getUserId()));
        });
        Integer count = memberMapper.pageQueryMembersCount(query);
        return PageVO.convert(pb.getPage(), pb.getLimit(), page, count);
    }

    @Override
    public MemberAccount saveMemberAccount(MemberAccountDTO memberAccount) {
        MemberAccount account=memberAccountRepository.findMemberAccountByUserId(memberAccount.getUserId());
        if(account!=null){
            throw new BizException("账号已存在");
        }
         account=memberAccountRepository.findMemberAccountByMobile(memberAccount.getMobile());
        if(account!=null){
            throw new BizException("手机号码已存在");
        }
        memberAccount.getRoleIds().forEach(rid->{
            MemberRole role=new MemberRole();
            role.setUserId(memberAccount.getUserId());
            role.setRoleId(rid);
            memberRoleRepository.save(role);
        });
        account=new MemberAccount();
        BeanUtils.copyProperties(memberAccount,account);
        String password = new BCryptPasswordEncoder().encode(memberAccount.getPassword());
        account.setPassword(password);
        account.setUserType(1);
        return memberAccountRepository.save(account);
    }

    @Override
    public MemberAccount updateMemberAccount(MemberAccountDTO memberAccount) throws BizException{
        MemberAccount account=memberAccountRepository.findById(memberAccount.getId()).get();
        if(account==null){
            throw new BizException("用户不存在");
        }
        List<MemberRole> mrs=memberRoleRepository.findMemberRolesByUserId(account.getUserId());
        memberRoleRepository.deleteInBatch(mrs);
        memberAccount.getRoleIds().forEach(rid->{
            MemberRole role=new MemberRole();
            role.setRoleId(rid);
            role.setUserId(memberAccount.getUserId());
            memberRoleRepository.save(role);
        });
        BeanUtils.copyProperties(memberAccount,account);
       return memberAccountRepository.save(account);
    }

    @Override
    public MemberAccount findMemberAccountMobile(String mobile) {
        return memberAccountRepository.findMemberAccountByMobile(mobile);
    }

    @Override
    public void updatePassword(MemberAccountDTO member) throws BizException{
        if(StringUtils.isEmpty(member.getUserId())){
            throw new BizException("用户编号不能为空");
        }
        if(StringUtils.isEmpty(member.getPassword())){
            throw new BizException("密码不能为空");
        }
        MemberAccount account=memberAccountRepository.findMemberAccountByUserId(member.getUserId());
        if(account==null){
            throw new BizException("账号不存在");
        }
        String password = new BCryptPasswordEncoder().encode(member.getPassword());
        account.setPassword(password);
        memberAccountRepository.save(account);
    }

    @Override
    public void updateStatus(MemberAccountDTO member) throws BizException {
        if(StringUtils.isEmpty(member.getUserId())){
            throw new BizException("用户编号不能为空");
        }
        if(null==member.getStatus()){
            throw new BizException("用户状态不能为空");
        }
        MemberAccount account=memberAccountRepository.findMemberAccountByUserId(member.getUserId());
        if(account==null){
            throw new BizException("账号不存在");
        }
        account.setStatus(member.getStatus());
        memberAccountRepository.save(account);
    }
}
